package com.jmyd.coupon.server.manager;

import com.jmyd.commons.domain.po.SysUser;
import com.jmyd.commons.enums.SystemErrorEnum;
import com.jmyd.commons.exception.CustomException;
import com.jmyd.coupon.server.domain.dto.SceneUseCouponDto;
import com.jmyd.coupon.server.domain.po.SceneCouponUseRecord;
import com.jmyd.coupon.server.mapper.SceneCouponDrawRecordMapper;
import com.jmyd.coupon.server.mapper.SceneCouponUseRecordMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author samphin
 * @since 2021/7/15 9:45
 */
@Component
public class SceneCouponManager {

    @Resource
    private SceneCouponDrawRecordMapper sceneCouponDrawRecordMapper;
    @Resource
    private SceneCouponUseRecordMapper sceneCouponUseRecordMapper;

    /**
     * 校验是否重复领取
     *
     * @param userId   用户ID
     * @param couponId 优惠券ID
     * @author samphin
     * @since 2021-7-15 09:47:11
     */
    public void validateDrawCoupon(String userId, Long couponId) {
        Example example = new Example(SceneCouponUseRecord.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("couponId", couponId);
        boolean bl = this.sceneCouponUseRecordMapper.selectCountByExample(example) > 0;
        if (bl) {
            throw new CustomException(SystemErrorEnum.SCENE_COUPON_IS_DRAW_ERROR);
        }
    }

    /**
     * 校验优惠券已被使用
     *
     * @param couponId 优惠券ID
     * @author samphin
     * @since 2021-7-15 09:47:11
     */
    public void validateIsUsedCoupon(Long couponId) {
        Example example = new Example(SceneCouponUseRecord.class);
        example.createCriteria()
                .andEqualTo("couponId", couponId);
        boolean bl = this.sceneCouponUseRecordMapper.selectCountByExample(example) > 0;
        if (bl) {
            throw new CustomException(SystemErrorEnum.SCENE_COUPON_CODE_IS_USED_ERROR);
        }
    }

    /**
     * 校验优惠券已被使用
     *
     * @param sysUser  用户信息
     * @param sceneUseCouponDto 使用优惠券业务参数
     * @author samphin
     * @since 2021-7-15 09:47:11
     */
    @Async
    public void saveUseRecord(SysUser sysUser, SceneUseCouponDto sceneUseCouponDto) {
        SceneCouponUseRecord sceneCouponUseRecord = new SceneCouponUseRecord();
        sceneCouponUseRecord.setCouponId(sceneUseCouponDto.getCouponId());
        sceneCouponUseRecord.setNickname(sysUser.getNickname());
        sceneCouponUseRecord.setUsername(sysUser.getUsername());
        sceneCouponUseRecord.setUserId(sysUser.getId());
        sceneCouponUseRecord.setBusinessId(sceneUseCouponDto.getBusinessId());
        sceneCouponUseRecord.setCreatedBy(sysUser.getId());
        sceneCouponUseRecord.setCreateTs(new Date());
        this.sceneCouponUseRecordMapper.insertSelective(sceneCouponUseRecord);
    }
}
